package server

import (
	"codeforces/src/task"
	"encoding/json"
	"fmt"
	"log"

	"github.com/Shopify/sarama"
)

func sendResp(producer sarama.AsyncProducer, respStrChan chan task.ITask, checkDone func(), logger *log.Logger) {
	sendChan := make(chan *sarama.ProducerMessage, 100)
	go func() {
		for {
			select {
			case resp := <-sendChan:

				producer.Input() <- resp
			case e := <-producer.Errors():
				log.Output(1, "producer err :"+e.Error())
			case <-producer.Successes():
			default:
				checkDone()
			}
		}
	}()
	for tsk := range respStrChan {
		resp := response{}
		if tsk.OccurErr() {
			resp.Status = "err"
			resp.Why = tsk.Error()
			resp.Data = ""
		} else {
			resp.Status = "ok"
			resp.Data = tsk.GetResult()
		}
		s, _ := json.Marshal(resp)
		message := &sarama.ProducerMessage{
			Topic: "cfResp",
			Key:   sarama.StringEncoder(tsk.GetKey()),
			Value: sarama.StringEncoder(s),
		}
		fmt.Println("send resp")
		sendChan <- message

	}
}
